package com.lz.sports.vm.config

import android.text.Editable
import android.text.TextUtils
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import com.lz.sports.bean.DeviceInfo
import com.lz.sports.bean.PageList
import com.lz.sports.core.ProjectManager
import com.lz.sports.db.DeviceDatabase
import com.lz.sports.vm.ListViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.*

class DeviceListViewModel : ListViewModel<DeviceInfo>() {
    //项目ID
    val projectId = ProjectManager.examProjectId()

    //搜索关键词
    val keywordStr = MutableLiveData<String>()
    //显示清除
    var showClear = MutableLiveData(false)
    //总数量
    val totalCount = MutableLiveData(0)

    private var listJob: Job? = null

    private var keyword: String? = null

    override fun onCreate(owner: LifecycleOwner) {
        limit = 1000 //分页时当根据适配器的实际大小来进行
        firstPageSearch()
    }

    private fun firstPageSearch() {
        listJob?.cancel()
        listJob = launch {
            flow { emit(findDeviceInfoList()) }
                .map { PageList(page, limit, it) }
                .flowOn(Dispatchers.IO)
                .onStart { updateDialogLoading(true); isLoading = true }
                .onCompletion { updateDialogLoading(false); isLoading = false }
                .collect {
                    pageListData.value = it
                    if (it.hasNext) pageAdd()
                }
        }
    }

    fun search() {
        this.keyword = keywordStr.value?.trim()
        this.page = 0
        firstPageSearch()
    }

    fun clearSearch() {
        if (!TextUtils.isEmpty(keyword)) {
            keyword = null
            this.page = 0
            firstPageSearch()
        }
    }

    override fun pagingNext() {
        listJob?.cancel()
        listJob = launch {
            flow { emit(findDeviceInfoList()) }
                .map { PageList(page, limit, it) }
                .flowOn(Dispatchers.IO)
                .onStart { isLoading = true }
                .onCompletion { isLoading = false }
                .collect {
                    pageListData.value = it
                    if (it.hasNext) pageAdd()
                }
        }
    }

    fun afterTextChanged(editable: Editable) {
        showClear.value = editable.isNotEmpty()
    }

    //获取数据
    private fun findDeviceInfoList(): List<DeviceInfo> {
        if (this.keyword != null) {
            return DeviceDatabase.get().findDeviceInfoList(this.keyword!!, projectId, page, limit)
        }
        return DeviceDatabase.get().findDeviceInfoList(projectId, page, limit)
    }
}